import flvjs from "flv.js";
import { useEffect, useState, useRef } from "react";
import styles from "./style.module.css";
import PropTypes from "prop-types";
import APIS from '../../api'

function Player({ src }) {
  const videoRef = useRef();

  const [url, setUrl] = useState('')

  // 获取 视频拉流地址
  useEffect(() => {
    getPullStreamUrl()
    return () => {
      stopPullStream()
    };
  }, []);

  const getPullStreamUrl = async () => {
    console.log('发送开摄像头命令')
    const res = await APIS.startPullCameraStreamCMDById(1234)
    console.log(res)
  }

  const stopPullStream = async () => {
    console.log('发送关摄像头命令')
    const res = await APIS.stopPullCameraStreamCMDById(1234)
    console.log(res)
  }

  useEffect(() => {
    let player;
    const video = videoRef.current;
    if (flvjs.isSupported()) {
      player = flvjs.createPlayer({
        type: "flv",
        isLive: true,
        url: src,
      });
      if (video) {
        player.attachMediaElement(videoRef.current);
        player.load();
        try {
          player.play();
        } catch (err) {
          console.log("自动播放出错", err);
        }
      }
      player.on(flvjs.ErrorTypes.NETWORK_ERROR, (err) => {
        console.log("flv.js 网络错误");
        console.log(err);
      });
    } else {
      alert("不支持");
      return;
    }
    return () => {
      console.log("Player 组件 clear func");
      console.log(player)
      video.srcObjet = null;
      video.src = "";
      // 销毁实例
      player.pause();
      player.unload();
      player.destroy();
      player = null;
    };
  }, []);

  return (
    <div className={styles.player}>
      <video src={src} className={styles.video} ref={videoRef}></video>
    </div>
  );
}

Player.propTypes = {
  src: PropTypes.string.isRequired,
};

export default Player;
